<template>
    <view class="goodsSku-panel">
        <view class="sku-top">
            <image :src="props.goodDetail?.mainPictures[0]" mode="scaleToFill"/>
            <view class="sku-top-tip">
                <view class="tip-price"><text class="sign">￥</text><text class="price">{{props.goodDetail?.price}}</text></view>
                <text class="tip-stock">库存:{{standardsInventory}}</text>
                <view class="tip-selected"><text>已选:{{showSelected}}</text></view>
            </view>
            <view class="sku-top-close"><uni-icons @click="close_btn" type="closeempty" size="24"></uni-icons></view>
        </view>
        <!-- 规格选择 -->
        <view class="sku-content">
            <!-- 一个规格 在此进行遍历 -->
            <view class="sku-content-item" v-for="item,index in props.goodDetail?.specs" :key="index">
                <view class="content-item-prop">{{item.name}}</view>
                <view class="content-item-attrs">
                    <view class="attrs-item" :class="el.isSelected==true?'active':''" v-for="el,i in item.values" :key="index" @tap="selectAttr(item,el)">{{el.name}}</view>
                </view>
            </view>
        </view>
        <!-- 数量选择 -->
        <view class="sku-number">
            <text class="number-title">数量</text>
            <view class="number-select">
                <!-- 数量控制选择 -->
                <button size="mini" @tap="number_minus">-</button>
                <input type="number" v-model="goodNumber" @blur="number_input_blur"/>
                <button size="mini" @tap="number_add">+</button>
            </view>
        </view>
        <view class="sku-buttons">
            <view class="button-addCart" @tap="btn_addCart">加入购物车</view>
            <view class="button-buy" @tap="btn_buy">立即购买</view>
        </view>
    </view>
</template>
<script setup lang="ts">
import { ref, watch, computed } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
//引入请求函数
import { reqAddCart } from "@/services/cart";


//父组件绑定的自定义事件
const emit = defineEmits<{
    (event:'close'):void,
    (event:"sendGoodSkuInfo"):void
}>()
//父组件绑定的属性 props.goodsDetail.price/inventory/specs
const props = defineProps(['goodDetail','skuId'])

onShow(()=>{
    // console.log(props.goodDetail);
})

//选择商品数量input值
let goodNumber = ref(1);
//选择的商品规格及属性值
let seletedProps = ref([]);


//对goodNumber值进行监视
watch(()=>goodNumber.value,(newVal,oldVal)=>{
    // console.log(newVal)
})
//计算属性:对已选规格进行处理展示
const showSelected = computed(()=>{
    let str = "";
    seletedProps.value.forEach(item => {
        str += item.propName + ':' + item.attrName + ' ';
    })
    return str;
})
//对选择好的规格的商品库存进行计算
const standardsInventory = computed(()=>{
    let currentId = getParamsIdByskus();
    let inventory:number = 0;
    //对props.goodDetail.skus进行遍历，找出库存
    props.goodDetail?.skus.forEach(item => {
        if(item.id == currentId){
            inventory = item.inventory;
            return ;
        }
    })
    //规格未选全，展示全部库存
    if(inventory == 0){
        return props.goodDetail?.inventory;
    }
    return inventory;
})

//规格选项的点击事件porp:规格名称 attr:选择属性项
const selectAttr = (prop:any, attr:any) => {
    // console.log(prop, attr);
    props.goodDetail.specs.forEach((item,index) => {
        if(item.id == prop.id){
            for(let i=0; i<item.values.length; i++){
                item.values[i].isSelected = false;
            }
        }
    })
    attr.isSelected = true;
    //收集选中的规格
    if(seletedProps.value.length > 0){
        let isAddOtherProp = true;
        seletedProps.value.forEach((item,index) => {
            if(item.id == prop.id){
                seletedProps.value[index] = {id:prop.id,propName:prop.name,attrName:attr.name};
                isAddOtherProp = false;  //是修改规格属性，不用添加其它规格
                return ;
            }
        });
        //已有规格下添加其它规格
        if(isAddOtherProp){
            seletedProps.value.push({id:prop.id,propName:prop.name,attrName:attr.name});
        }
        return;
    } else {
        //添加规格
        seletedProps.value.push({id:prop.id,propName:prop.name,attrName:attr.name});
    }
}

//数量输入框失去焦点事件
const number_input_blur = (env:any) => {
    //对输入数值进行校验
    let str = env.detail.value;
    if(Number.isNaN(Number(str)) || Number(str) < 1 || Number(str) > 100){
        //输入非法
        uni.showToast({icon:"none",title:"输入非法!"});
        goodNumber.value = 1;
    }
}

//数量添加与减少的tap事件
const number_add = () => {
    if(goodNumber.value > 99) return;
    goodNumber.value ++;
}
const number_minus = () => {
    if(goodNumber.value < 2) return;
    goodNumber.value --;
}

//对props.goodDetail.skus进行处理，取出选择的规格对应的id值
const getParamsIdByskus = () => {
    for(let i=0; i<props.goodDetail?.skus.length; i++){
        let flag = false;  //是否还要继续循环找
        let currentStr = '';
        let selectedAttr = [];
        //对每一项skus的item的value拼串
        for(let j=0; j<props.goodDetail.skus[i].specs.length; j++){
            currentStr += props.goodDetail.skus[i].specs[j].name +'-'+props.goodDetail.skus[i].specs[j].valueName +' ';
        }
        //对选择好的规格项进行拼串
        for(let k=0; k<seletedProps.value.length; k++){
            selectedAttr.push(seletedProps.value[k].attrName);
        }
        //如果当前选择的规格没有选择全，应当终止该方法
        if(props.goodDetail?.specs.length != selectedAttr.length) return;

        // console.log('skus每一项拼接字符串',currentStr)
        // console.log("选择好的属性值",selectedAttr);
        flag = false;
        //对比字符串
        selectedAttr.forEach(item => {
            if(currentStr.includes(item) == false){
                flag = true;
                //置空
                let currentStr = '';
                let selectedAttr = [];
                return ;
            }
        })
        //判断是否找到
        if(flag == false){
            // console.log("找到id了",props.goodDetail?.skus[i].id);
            return props.goodDetail?.skus[i].id;
        }
    }
}

//popup关闭按钮
const close_btn = () => {
    emit('close');  //关闭popup弹窗
    emit('sendGoodSkuInfo',showSelected.value);  //给父组件传递已选规格
}

//加入购物车和立即购买按钮
const btn_addCart = async () => {
    //对skus中进行遍历取出id。(傻逼接口,稿半天不知道哪个id,操)
    let skuId = getParamsIdByskus();
    if(skuId == undefined){
        return uni.showToast({icon:"none",title:"请选择商品规格"});
    }
    let res = await reqAddCart(skuId, goodNumber.value);
    console.log('加入购物车api',res);
    uni.showToast({icon:"success",title:"商品添加成功"});
    //关闭popup
    setTimeout(() => {
        emit('close');
    }, 500);
}
const btn_buy = () => {
    // console.log('收集到商品选中的属性',seletedProps.value);
    // console.log('选择的规格id为',getParamsIdByskus());
    let skuId = getParamsIdByskus();
    let count = goodNumber.value;
    //立即购买，跳转到订单结算页query:skuId= & count= & addressId?=
    uni.navigateTo({url:`/orderPages/createOrder/createOrder?skuId=${skuId}&count=${count}&addressId=`});
}

</script>

<style lang="scss">
.goodsSku-panel{
    padding: 0 30rpx;
    border-radius: 10rpx 10rpx 0 0;
    position: relative;
    background-color: #fff;

    // 顶部区域
    .sku-top{
        width:100%;
        height:240rpx;
        padding:30rpx 0;
        display:flex;

        image{
            width:140rpx;
            height:140rpx;
            margin-top:30rpx;
        }

        .sku-top-tip{
            width:100%;
            height:160rpx;
            margin-left:30rpx;
            margin-top:20rpx;
            display:flex;
            flex-direction:column;

            .tip-price{
                color:red;
                .sign{
                    font-size:12px;
                }
                .price{
                    font-size:22px;
                }
            }
            .tip-stock{
                margin:15rpx 0;
                font-size:12px;
                color:skyblue;
            }
            .tip-selected{
                font-size:14px;
            }
        }

        .sku-tip-close{
            width:50rpx;
            height:50rpx;
            background-color:red;
        }
    }
    // 规格选择
    .sku-content{
        width:100%;
        height:100%;
        display:flex;
        flex-direction:column;

        // 一个规格项
        .sku-content-item {
            width:100%;
            height:100%;

            .content-item-prop{
                width:100%;
                height:80rpx;
                color:#999aaa;
                font-size:16px;
                text-align:left;
                line-height:80rpx;
            }
            .content-item-attrs{
                width:100%;
                height:100%;
                display:flex;
                flex-wrap:wrap;

                .attrs-item {
                    display:flex;
                    color:#999aaa;
                    font-size:16px;
                    padding:10rpx 20rpx;
                    border-radius:5px;
                    margin-right:20rpx;
                }
                .active{
                    border:1px solid #999aaa;
                    background-color:#ebeef5;
                }
            }
        }
    }
    //数量选择
    .sku-number{
        width:100%;
        height:80rpx;
        margin:60rpx 0;
        display:flex;
        justify-content:space-between;

        .number-title{
            color:black;
            font-size:18px;
            line-height:80rpx;
        }
        .number-select{
            display:flex;
            
            button{
                width:60rpx;
                height:60rpx;
                background-color:#f5f7fa;
            }
            input{
                width:80rpx;
                height:60rpx;
                padding:0 20rpx;
                font-size:12px;
                background-color:#f5f7fa;
            }
        }
    }
    //底部按钮
    .sku-buttons{
        width:100%;
        height:80rpx;
        margin-bottom:40rpx;
        border-radius:50px;
        display:flex;

        .button-addCart {
            width:50%;
            height:100%;
            text-align:center;
            border-radius:50px 0 0 50px;
            line-height:80rpx;
            color:#fff;
            background-color:#f56c6c;
        }
        .button-buy {
            width:50%;
            height:100%;
            text-align:center;
            border-radius:0 50px 50px 0;
            line-height:80rpx;
            color:#fff;
            background-color:#909399;
        }
    }
}
</style>